import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:zrjz/api/auth_repository.dart';
import 'package:zrjz/comm/constants/api_constants.dart';
import 'package:zrjz/comm/constants/app_constant.dart';
import 'package:zrjz/comm/http/http_result.dart';
import 'package:zrjz/comm/utils/event_bus.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/utils/util.dart';
import 'package:zrjz/comm/widget/dialog/verify_code_dialog/verify_code_dialog.dart';
import 'package:zrjz/comm/widget/dialog/verify_code_dialog/verify_code_dialog_controller.dart';
import 'package:zrjz/comm/widget/global_web/global_web_page.dart';
import 'package:zrjz/entity/response/user_login.dart';
import 'package:zrjz/globalService/user_service.dart';
import 'package:zrjz/modules/main/main_page.dart';

import 'bind_phone_state.dart';

class BindPhoneController extends GetxController {
  final BindPhoneState state = BindPhoneState();
  final AuthRepository authRepository = Get.find();

  late String platform;
  late String openId;

  bool isChecked = false;
  String? mobilePhoneErrorText; //表单的错误信息展示
  String? codeErrorText;
  String? phone;
  String? code;

  // 勾选协议
  void handlerSelectAgreeCheckbox() {
    isChecked = !isChecked;
    update();
  }

  // 重置电话的错误文本
  void resetPhoneErrorText() {
    mobilePhoneErrorText = null;
    update();
  }

  /// 执行手机号码的绑定
  void doBindPhone() {
    mobilePhoneErrorText = null;
    codeErrorText = null;
    update();

    var phoneController = state.formData['phone']!['controller'];
    var passwordController = state.formData['code']!['controller'];

    phone = phoneController.text;
    code = passwordController.text;

    Log.d('phone:$phone code:$code');

    if (!isChecked) {
      SmartDialog.showToast('请先阅读并同意协议'.tr);
    } else if (Utils.isEmpty(phone)) {
      mobilePhoneErrorText = "电话号码不能为空";
      update();
    } else if (Utils.isEmpty(code)) {
      codeErrorText = "验证码不能为空";
      update();
    } else if (!Utils.isChinaPhoneNumber(phone)) {
      mobilePhoneErrorText = "请检查电话号码";
      update();
    } else {
      //执行密码登录
      _request2BindPhone();
    }
  }

  // 执行绑定手机号码的逻辑，绑定到第三方登录账号
  void _request2BindPhone() async {
    // //获取到数据
    // SmartDialog.showLoading();
    // String registrationId = UserService.to.getRegistrationId;
    // // var result = await authRepository.socialiteBindPhone(platform, openId, phone, code, registrationId);
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   //保存Token，去首页
    //   _handleLoginSuccess(result.data!);
    // } else {
    //   _handleErrorMessage(result);
    // }
  }

  /// 登录成功的统一处理 - 去首页
  void _handleLoginSuccess(UserLogin result) {
    //保存Token，去首页
    final token = result.token;
    UserService.to.setToken(token);

    //发送通知请求用户详情数据
    bus.emit(AppConstant.eventProfile2Refresh, true);

    //使用SingleTask启动模式去首页
    MainPage.startInstance();
  }

  /// 处理网络请求注册的表单错误
  void _handleErrorMessage(HttpResult<dynamic> result) {
    String? errorMessage = result.errorMsg;
    SmartDialog.showToast(errorMessage ?? '未知错误'.tr);

    Map<String, dynamic>? json = result.getErrorJson();

    handleFormError(json, 'phone', (str) {
      mobilePhoneErrorText = str;
    });
    handleFormError(json, 'sms_verification_code', (str) {
      codeErrorText = str;
    });
  }

  /// 默认的App Dialog
  void showVerifyCodedDialog() {
    //隐藏全部的软键盘与焦点
    _phoneFocusNode?.unfocus();
    _codeFocusNode?.unfocus();

    //校验手机号码不能为空
    phone = state.formData['phone']!['controller'].text;
    if (Utils.isEmpty(phone)) {
      mobilePhoneErrorText = "电话号码不能为空";
      update();
    } else {
      SmartDialog.show(
        usePenetrate: false,
        debounce: true,
        clickMaskDismiss: false,
        onDismiss: () {
          //每次取消弹窗都要手动删除弹窗的Controller，不然无法每次弹出都请求接口
          Get.delete<VerifyCodeDialogController>();
        },
        builder: (context) => VerifyCodeDialog(
          confirmAction: (key, code) {
            //发送验证码
            _requestSendSMS(key, code);
          },
        ),
      );
    }
  }

  /// 请求接口，发送验证码
  void _requestSendSMS(String? key, String? code) async {
    // //获取到数据
    // SmartDialog.showLoading();
    // var result = await authRepository.sendPhoneSMS('bind_phone', phone, key, code);
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   //成功之后开始倒计时
    //   _startCountDown();
    // } else {
    //   String? errorMessage = result.errorMsg;
    //   SmartDialog.showToast(errorMessage ?? '未知错误'.tr);
    // }
  }

  // =========================== 倒计时控制 ===========================

  final int _initialTime = 60; // 初始倒计时时间（秒）
  int countdownTime = 0; // 当前倒计时剩余时间（秒）
  Timer? countdownTimer;
  bool isCounting = false;

  /// 开启倒计时
  void _startCountDown() {
    countdownTime = _initialTime;
    isCounting = true;
    update();

    //每秒的倒计时
    countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdownTime > 0) {
        countdownTime--;
      } else {
        isCounting = false;
        countdownTimer?.cancel(); // 取消计时器
      }
      update();
    });
  }

  // =========================== 焦点控制 ===========================

  FocusNode? _phoneFocusNode;
  FocusNode? _codeFocusNode;

  void _onPhoneFocusChange() {
    if (_phoneFocusNode?.hasFocus == false) {
      mobilePhoneErrorText = null;
      update();
    }
  }

  @override
  void onInit() {
    super.onInit();
    platform = Get.arguments['platform'];
    openId = Get.arguments['openId'];

    _phoneFocusNode = state.formData['phone']!['focusNode'];
    _codeFocusNode = state.formData['code']!['focusNode'];
  }

  @override
  void onReady() {
    super.onReady();

    //Phone输入框的失去焦点监听
    _phoneFocusNode?.addListener(_onPhoneFocusChange);
  }

  @override
  void onClose() {
    super.onClose();

    _phoneFocusNode?.removeListener(_onPhoneFocusChange);
    _phoneFocusNode = null;

    countdownTimer?.cancel(); // 取消计时器
  }

  //去Web页面
  void gotoUserAgreementPage() {
    GlobalWebPage.startInstance("免责条款", ApiConstants.userAgreementUrl);
  }

  //去Web页面
  void gotoPricacyPolicyPage() {
    GlobalWebPage.startInstance("隐私协议", ApiConstants.privacyPolicyUrl);
  }
}
